<template>
	<view class="login-form">
		<uni-forms ref="formRef" :modelValue="formData" :rules="rules">
			<uni-forms-item name="username">
				<uni-easyinput v-model="formData.username" placeholder="请输入用户名" prefixIcon="person" />
			</uni-forms-item>
			<uni-forms-item name="password">
				<uni-easyinput v-model="formData.password" placeholder="请输入密码" prefixIcon="locked" type="password" />
			</uni-forms-item>
			<uni-forms-item>
				<button @click="showCaptcha"
					:style="{ backgroundColor: getTheme.themeColor, color: '#fff', fontSize: '14px' }"
					:loading="loading">立即登录</button>
			</uni-forms-item>
		</uni-forms>

		<view class="container">
			<go-captcha-uni v-if="showCaptchaModal" type="slide" :config="config" :theme="theme" :data="captchaData"
				ref="captchaRef" @event-move="handleMove" @event-refresh="handleRefresh" @event-close="handleClose"
				@event-confirm="handleConfirm" />
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref } from "vue";
	import { loginApi, userApi } from "@/api/index";
	import { useAuthStore } from "@/stores/auth";
	const authStore = useAuthStore();
	const getTheme = authStore.getTheme();
	const loading = ref(false); // 登录按钮加载状态
	const formRef = ref<any>(null); // 表单引用
	const captchaRef = ref<any>(null);
	const showCaptchaModal = ref(false);
	// 验证码配置
	const config = ref({
		title: "请拖动滑块完成拼图",
		showTheme: true
	});
	const pages = getCurrentPages(); // 获取页面栈
	// 主题样式
	const theme = ref({});

	// 验证码数据
	const captchaData = ref({});

	// 显示验证码
	const showCaptcha = async () => {
		await formRef.value.validate();

		showCaptchaModal.value = true;
		loadCaptchaData();
	};

	// 表单数据
	const formData = ref({
		username: "",
		password: "",
		captcha_token: ""
	});

	// 表单验证规则
	const rules = ref({
		username: {
			rules: [
				{
					required: true,
					errorMessage: "请输入账号"
				}
			]
		},
		password: {
			rules: [
				{
					required: true,
					errorMessage: "请输入密码"
				}
			]
		}
	});

	//获取验证码id
	const loadCaptchaData = async () => {
		try {
			const res = await loginApi.getcaptcha();
			captchaData.value = res.data;
			captchaParams.value.key = res.data.key;
		} catch (error) {
			uni.showToast({
				icon: "error",
				title: error.message
			});
		}
	};

	// 滑块移动事件
	const handleMove = (x : number, y : number) => {
		// console.log("滑块位置:", x, y);
	};

	// 刷新验证码
	const handleRefresh = () => {
		// console.log("用户点击了刷新");
		loadCaptchaData();
	};

	// 手动刷新验证码（暴露给父组件的方法）
	const refreshCaptcha = () => {
		captchaRef.value?.refresh();
	};
	// 关闭验证码
	const handleClose = () => {
		// console.log("用户关闭了验证码");
		showCaptchaModal.value = false;
	};

	const captchaParams = ref({
		key: "",
		answer: ""
	});
	// 确认验证
	const handleConfirm = async (point : { x : number; y : number }, reset : () => void) => {
		captchaParams.value.answer = Object.values(point).toString();

		try {
			const res = await loginApi.checkcaptcha(captchaParams.value);
			if (res.status === 0) {
				formData.value.captcha_token = res.data;
				uni.showToast({
					title: "验证成功",
					icon: "error"
				});
				handleLogin();
			} else {
				uni.showToast({
					title: res.message,
					icon: "error"
				});
			}
		} catch (error) {
			uni.showToast({
				title: error.message
			});
		}
	};

	// 处理登录
	const handleLogin = async () => {
		loading.value = true;

		await loginApi.login(formData.value).then((res) => {
			if (res.status === 0) {
				authStore.setToken(res.data.token);
				uni.showToast({ icon: "success", title: "登录成功" });
				loading.value = false;
			} else {
				refreshCaptcha();
				loading.value = false;

				uni.showToast({
					title: res.message,
					duration: 2000,
					icon: "error"
				});

				return;
			}
		});

		console.log(authStore.getToken(), 34354);

		await userApi.getUserinfo().then((res) => {
			authStore.setUser(res.data);
		});

		await loginApi.getConfig().then((res) => {
			authStore.setConfig(res.data);
		});

		uni.navigateTo({ url: "/pages/home/home" });
	};

	const getUser = async () => {
		await userApi.getUserinfo().then((res) => {
			authStore.setUser(res.data);
			getConfig();
		});
	};

	const getConfig = async () => {
		await loginApi.getConfig().then((res) => {
			authStore.setConfig(res.data);

			uni.navigateTo({ url: "/pages/home/home" });
		});
	};

	// 跳转到注册页面
	const navigateToRegister = () => {
		uni.navigateTo({
			url: "/pages/register/register"
		});
	};
</script>

<style lang="scss">
	.login-form {
		margin-top: 20px;

		.container {
			position: fixed;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			z-index: 999;
		}

		.login-btn {
			width: 100%;
			border-radius: 4px;
		}
	}
</style>